﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using DataLayer;

public partial class tab_modifyshare : System.Web.UI.Page
{
   public int TabID
   {
      get
      {
         try
         {
            int result = Convert.ToInt32(Request.QueryString["id"]);
            if (result < 1)
               return -1;
            else
               return result;
         }
         catch
         {
         }

         return -1;
      }
   }
   protected override PageStatePersister PageStatePersister
   {
      get
      {
         return new SessionPageStatePersister(this.Page);
      }
   }
   protected DataTable tbl_AccessRights
   {
      get
      {
         DataTable tbl = (DataTable)ViewState["TBL"];
         if (tbl == null)
         {
            tbl = new DataTable("tbl");
            tbl.Columns.Add("UserID", typeof(Guid));
            tbl.Columns.Add("AccessLevel", typeof(int));
            tbl.Columns.Add("Source");
            tbl.Columns.Add("DisplayName");
            tbl.Columns.Add("User_Delete", typeof(bool));
            tbl.Columns.Add("isRole", typeof(bool));
            tbl.Columns.Add("Tab_EditName", typeof(bool));
            tbl.Columns.Add("Tab_Read", typeof(bool));
            tbl.Columns.Add("Tab_Share", typeof(bool));
            tbl.Columns.Add("Tab_Delete", typeof(bool));
            tbl.Columns.Add("Tab_AddWidgets", typeof(bool));
            tbl.Columns.Add("Tab_ChangeLayout", typeof(bool));
            tbl.Columns.Add("Tab_ChangeTheme", typeof(bool));
            tbl.Columns.Add("Widget_Edit", typeof(bool));
            tbl.Columns.Add("Widget_Reorder", typeof(bool));
            tbl.Columns.Add("Widget_Delete", typeof(bool));
            tbl.Columns.Add("Widget_EditTitle", typeof(bool));
            tbl_AccessRights = tbl;
         }

         return tbl;
      }
      set
      {
         ViewState["TBL"] = value;
      }
   }
   protected void Page_Load(object sender, EventArgs e)
   {
      bool noPermission = false;
      if (TabID < 1)
      {
         noPermission = true;
      }

      //has shares if..
      if (!noPermission)
      {
         using (var db = DatabaseHelper.GetDashboardData())
         {
            var UserTabRow = from p in db.UserTabs
                             where p.TabId == TabID && p.UserID == Functions.GetUserProviderKey()
                             select p.AccessLevel;

            noPermission = true;
            foreach (var AccessLevel in UserTabRow)
            {
               if (TabAccessLevelFunctions.UserHasPermission(AccessLevel, TabAccessLevel.Tab_Share))
               {
                  noPermission = false;
                  break;
               }
            }

            if (!noPermission)
            {
               LoadData(db);
              if(tbl_AccessRights.Rows.Count < 1)
               {
                  //no tab share, redirect
                  Response.Redirect("tab_share.aspx?id=" + TabID);
               }
            }

            if (!noPermission && !IsPostBack)
            {
               Panel_SetRights.Visible = true;
               var T = db.Tabs.Where(p => p.ID == TabID).First();
               lbl_Tab.Text = T.Title;
               DataView DV = new DataView();
               DV.Table = tbl_AccessRights;
               DV.Sort = "DisplayName";
               GV_AccessRights.DataSource = DV;
               GV_AccessRights.DataBind();
               //btn_Next1_Click(null, null);
            }
         }
      }

      if (noPermission)
      {
         Panel_SetRights.Visible = false;
         lbl_Tab.Text += "<br>You have no permission to edit share permissions";
         return;
      }
   }
   protected void LoadData(NexusDataContext db)
   {
      var UT = from p in db.UserTabs
               where p.TabId == TabID && p.Deleted == false && p.UserID != Functions.GetUserProviderKey() && p.RoleID == Constants.Role_Individual
               select new { p.AccessLevel, p.UserID, UserName = p.aspnet_User.UserName };

      var SA = from p in db.Tab_ShareActivations
               where p.TabID == TabID
               select p;

      var RT = from p in db.RoleTabs
               join R in db.aspnet_Roles on p.RoleID equals R.RoleId
               where p.TabId == TabID
               select new { p.AccessLevel, p.RoleID, R.RoleName }; 
      
      DataTable tbl = tbl_AccessRights;
      tbl.Rows.Clear();
      if (UT.Count() > 0 || SA.Count() > 0 || RT.Count() > 0)
      {
         //tab is already set for shares
         //list out the shares
         foreach (var u in UT)
         {
            DataRow row = tbl.NewRow();
            TabAccessLevel[] lvls = TabAccessLevelFunctions.GetAccessLevels(u.AccessLevel);
            row["AccessLevel"] = u.AccessLevel;
            row["DisplayName"] = u.UserName;
            row["Source"] = "UT";
            row["UserID"] = u.UserID;
            row["User_Delete"] = false;
            row["Tab_Read"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Tab_Read);
            row["Tab_EditName"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Tab_EditName);
            row["Tab_Share"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Tab_Share);
            row["Tab_Delete"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Tab_Delete);
            row["Tab_AddWidgets"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Tab_AddWidgets);
            row["Tab_ChangeLayout"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Tab_ChangeLayout);
            row["Tab_ChangeTheme"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Tab_ChangeTheme);
            row["Widget_Edit"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Widget_Edit);
            row["Widget_Reorder"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Widget_Reorder);
            row["Widget_Delete"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Widget_Delete);
            row["Widget_EditTitle"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Widget_EditTitle);
            tbl.Rows.Add(row);
         }

         foreach (var u in RT)
         {
            DataRow row = tbl.NewRow();
            TabAccessLevel[] lvls = TabAccessLevelFunctions.GetAccessLevels(u.AccessLevel);
            row["DisplayName"] = "Role: " + u.RoleName;
            row["Source"] = "RT";
            row["AccessLevel"] = u.AccessLevel;
            row["UserID"] = u.RoleID;
            row["User_Delete"] = false;
            row["Tab_Read"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Tab_Read);
            row["Tab_EditName"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Tab_EditName);
            row["Tab_Share"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Tab_Share);
            row["Tab_Delete"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Tab_Delete);
            row["Tab_AddWidgets"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Tab_AddWidgets);
            row["Tab_ChangeLayout"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Tab_ChangeLayout);
            row["Tab_ChangeTheme"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Tab_ChangeTheme);
            row["Widget_Edit"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Widget_Edit);
            row["Widget_Reorder"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Widget_Reorder);
            row["Widget_Delete"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Widget_Delete);
            row["Widget_EditTitle"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Widget_EditTitle);
            tbl.Rows.Add(row);
         }

         foreach (var u in SA)
         {
            DataRow row = tbl.NewRow();
            TabAccessLevel[] lvls = TabAccessLevelFunctions.GetAccessLevels(u.AccessLevel);
            row["DisplayName"] = (u.UserName.Length > 0 ? u.UserName : u.Email) + "[Pending]";
            row["Source"] = "SA";
            row["UserID"] = u.ID;
            row["AccessLevel"] = u.AccessLevel;
            row["User_Delete"] = false;
            row["Tab_Read"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Tab_Read);
            row["Tab_EditName"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Tab_EditName);
            row["Tab_Share"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Tab_Share);
            row["Tab_Delete"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Tab_Delete);
            row["Tab_AddWidgets"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Tab_AddWidgets);
            row["Tab_ChangeLayout"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Tab_ChangeLayout);
            row["Tab_ChangeTheme"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Tab_ChangeTheme);
            row["Widget_Edit"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Widget_Edit);
            row["Widget_Reorder"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Widget_Reorder);
            row["Widget_Delete"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Widget_Delete);
            row["Widget_EditTitle"] = TabAccessLevelFunctions.UserHasPermission(lvls, TabAccessLevel.Widget_EditTitle);
            tbl.Rows.Add(row);
         }
         tbl_AccessRights = tbl;
      }
   }

   protected void btn_Confirm_Click(object sender, EventArgs e)
   {
      //delete those that are deleted
      //update the rights of everyone else

      DataTable tbl = tbl_AccessRights;
      using (var db = DatabaseHelper.GetDashboardData())
      {
         for (int i = 0; i < GV_AccessRights.Rows.Count; i++)
         {
            GridViewRow Row = GV_AccessRights.Rows[i];
            if (Row.RowType == DataControlRowType.DataRow)
            {
               string Source = GV_AccessRights.DataKeys[Row.RowIndex][0].ToString();
               
               int SourceType = 0;
               if (Source == "SA")
                  SourceType = 1;
               else if (Source == "RT")
                  SourceType = 2;

               Guid UserID = (Guid)GV_AccessRights.DataKeys[Row.RowIndex][1];

               DataRow[] Rows = tbl.Select("Source='" + Source + "' and UserID='" + UserID.ToString().Replace("'", "''") + "'");
               if (Rows.Length > 0)
               {
                  bool toDelete = (Row.FindControl("cb_DeleteUser") as CheckBox).Checked;
                  if (toDelete)
                  {
                     switch (SourceType)
                     {
                        case 0:
                           var obj = (from p in db.UserTabs
                                      where p.TabId == TabID && p.UserID == UserID
                                      select p).Single();
                           db.UserTabs.DeleteOnSubmit(obj);
                           break;
                        case 1:
                           var obj1 = (from p in db.Tab_ShareActivations
                                      where p.ID == UserID
                                      select p).Single();
                           db.Tab_ShareActivations.DeleteOnSubmit(obj1);
                           break;
                        case 2:
                           var obj2 = (from p in db.RoleTabs
                                      where p.RoleID == UserID && p.TabId == TabID
                                      select p).Single();
                           db.RoleTabs.DeleteOnSubmit(obj2);

                           //Delete all role tabs in user tabs
                           db.ExecuteCommand("delete from UserTab where TabId={0} and RoleID={1}", new object[] { TabID, UserID });
                           /*
                           db.UserTabs.DeleteAllOnSubmit((from p in db.UserTabs
                                                          where p.TabId == TabID && p.RoleID == UserID
                                                          select p));
                            */
                           break;
                     }
                  }
                  else
                  {
                     //Get permission only if no delete indicated
                     foreach (DataRow row in Rows)
                     {
                        row["Tab_Read"] = (Row.FindControl("cb_Read") as CheckBox).Checked;
                        row["Tab_EditName"] = (Row.FindControl("cb_Tab_EditName") as CheckBox).Checked;
                        row["Tab_Share"] = (Row.FindControl("cb_Tab_Share") as CheckBox).Checked;
                        row["Tab_Delete"] = (Row.FindControl("cb_Tab_Delete") as CheckBox).Checked;
                        row["Tab_AddWidgets"] = (Row.FindControl("cb_Tab_AddWidgets") as CheckBox).Checked;
                        row["Tab_ChangeLayout"] = (Row.FindControl("cb_Tab_ChangeLayout") as CheckBox).Checked;
                        row["Tab_ChangeTheme"] = (Row.FindControl("cb_Tab_ChangeTheme") as CheckBox).Checked;
                        row["Widget_Edit"] = (Row.FindControl("cb_Widget_Edit") as CheckBox).Checked;
                        row["Widget_Reorder"] = (Row.FindControl("cb_Widget_Reorder") as CheckBox).Checked;
                        row["Widget_Delete"] = (Row.FindControl("cb_Widget_Delete") as CheckBox).Checked;
                        row["Widget_EditTitle"] = (Row.FindControl("cb_Widget_EditTitle") as CheckBox).Checked;

                        int AccessLevel = TabAccessLevelFunctions.GeneratePermissionLevel(false,
         (bool)row["Tab_Read"],
         (bool)row["Tab_EditName"],
         (bool)row["Tab_Share"],
         (bool)row["Tab_Delete"],
         (bool)row["Tab_AddWidgets"],
         (bool)row["Tab_ChangeLayout"],
         (bool)row["Tab_ChangeTheme"],
         (bool)row["Widget_Edit"],
         (bool)row["Widget_Reorder"],
         (bool)row["Widget_Delete"],
         (bool)row["Widget_EditTitle"]);

                        row["AccessLevel"] = AccessLevel;
                        switch (SourceType)
                        {
                           case 0:
                              var obj = (from p in db.UserTabs
                                         where
                                            p.TabId == TabID && p.UserID == UserID
                                         select p).Single();
                              obj.AccessLevel = AccessLevel;
                              break;
                           case 1:
                              var obj1 = (from p in db.Tab_ShareActivations
                                         where p.ID == UserID
                                         select p).Single();
                              obj1.AccessLevel = AccessLevel;
                              break;
                           case 2:
                              var obj2 = (from p in db.RoleTabs
                                          where p.RoleID == UserID && p.TabId == TabID
                                         select p).Single();
                              obj2.AccessLevel = AccessLevel;

                              //update permissions of all existing user tabs
                              db.ExecuteCommand("update UserTab set AccessLevel={2} where TabId={0} and RoleID={1}", new object[] { TabID, UserID, AccessLevel });
                              break;
                        }
                     }
                  }
               }
            }
         }
         db.SubmitChanges();
         LoadData(db);
      }
      DataView DV = new DataView();
      DV.Table = tbl_AccessRights;
      DV.Sort = "DisplayName";
      GV_AccessRights.DataSource = DV;
      GV_AccessRights.DataBind();
   }

   public static int GeneratePermissionLevel(bool Owner, bool Tab_Read, bool Tab_EditName, bool Tab_Share, bool Tab_Delete, bool Tab_AddWidgets, bool Tab_ChangeLayout, bool Tab_ChangeTheme, bool Widget_Edit, bool Widget_Reorder, bool Widget_Delete, bool Widget_EditTitle)
   {
      if (Owner)
         return 0;
      else
      {
         string PermissionLevel = (Tab_Read ? "0" : "1") +
                                 "111111111111111111111" +
                                  (Widget_EditTitle ? "0" : "1") +
                                  (Widget_Delete ? "0" : "1") +
                                  (Widget_Reorder ? "0" : "1") +
                                  (Widget_Edit ? "0" : "1") +
                                  (Tab_ChangeTheme ? "0" : "1") +
                                  (Tab_ChangeLayout ? "0" : "1") +
                                  (Tab_AddWidgets ? "0" : "1") +
                                  (Tab_Delete ? "0" : "1") +
                                  (Tab_Share ? "0" : "1") +
                                  (Tab_EditName ? "0" : "1");
         //Response.Write(PermissionLevel + "<br>");
         return Convert.ToInt32(PermissionLevel, 2);
      }
   }
}
